//
//  ITWebViewController(js).m
//  InTubePro
//
//  Created by seven on 2020/2/6.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITWebViewController(js).h"

#import "ITNetWorkManager.h"

@implementation ITWebViewController(js)

- (void)willDealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self AppEventMessage:3];
    [self releasejSFunctions];
    [super willDealloc];
}

- (void)releasejSFunctions{
    [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"nativeMethod"];
}
- (void)setupJSFunctions{
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"nativeMethod"];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignActive) name:UIApplicationWillResignActiveNotification object:nil];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    [self JSBridgeWithMessageName:message.name databody:message.body];
}

#pragma mark - 应用状态
- (void)AppEventMessage:(int)type{
    MainDelay(0.1, ^{
        [self postJsMethod:@"AppEventMessage" info:@{@"type": @(type)}];
    });
}

#pragma mark - ios -> js
- (void)postJsMethod:(NSString *)method info:(NSDictionary *)info{
    NSString *value = info;
    if ([value isKindOfClass:NSDictionary.class] || [info isKindOfClass:NSArray.class]) {
        value = info.jsonStringEncoded;
    }
    NSString *js = [method stringByAppendingFormat:@"(%@)", value];
    [self.wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        NSLog(@"obj: %@; error:%@", obj, error.localizedDescription);
    }];
}

#pragma mark - action
- (void)JSBridgeWithMessageName:(NSString *)functionName databody:(id)body{
    NSDictionary *dic = body;
    if ([body isKindOfClass:[NSString class]]) {
        NSData *data = [(NSString *)body dataUsingEncoding:(NSUTF8StringEncoding)];
        dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    }
    NSString *funName = dic[@"funName"];
    if (funName && funName.length > 0) {
        funName = [funName stringByAppendingString:@":"];
    }
    @weakify(self);
    SEL action = NSSelectorFromString(funName);
    if ([self respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [weak_self performSelector:action withObject:dic];
#pragma clang diagnostic pop
    }
}

/**关闭web*/
- (void)closeMe:(NSDictionary *)info{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showToast:(NSDictionary *)info{
    NSString *toast = info[@"content"];
    if (toast) {
        [self.view showInfo:toast];
    }
}

- (void)openSchemeUrl:(NSDictionary *)info{
    NSString *url = info[@"url"];
    if (url) {
        [UIApplication.sharedApplication openURL:[NSURL URLWithString:url] options:nil completionHandler:nil];
    }
}

- (void)isInstallApp:(NSDictionary *)info{
    NSString *pkg = info[@"pkg"];
    BOOL ret = [UIApplication.sharedApplication canOpenURL:[NSURL URLWithString:pkg]];
    [self postJsMethod:@"isInstallAppCallback" info:@{@"result": @(ret)}];
}

- (void)openURI:(NSDictionary *)info{
    [self openWebview:info];
}
- (void)openWebview:(NSDictionary *)info{
    NSString *path = info[@"path"];
    if (path) {
        [ITWebViewController openUrl:path];
    }
}

- (void)getHeaders:(NSDictionary *)info{
    NSMutableDictionary *header = [ITNetWorkManager.defaultManager defaultHeader];
    NSString *client = header[@"User-Agent-Client"];
    client = [client stringByReplacingCharactersInRange:NSMakeRange(0, 3) withString:@"h5"];
    header[@"User-Agent-Client"] = client;
    [self postJsMethod:@"getHeadersCallback" info:header];
}


- (void)getUserInfo:(NSDictionary *)info{
    WEAKSELF
    ITUserInfo*user = ITUserManager.currentMember;
    [ITUserManager.shareManager getMemberInfo:^(ITUserInfo * _Nonnull member, ITNetWorkModel * ret) {
        [weak_self postJsMethod:@"memberInfoCallback" info:@{@"data":ret.data, @"status": @(ret.code)}];
    }];
}


-(void)reportTackEvent:(NSDictionary *)info{
    id eventNo = info[@"eventNo"];
    NSString *paramStr = info[@"keyValuesStr"];
    NSDictionary *params = nil;
    if (![AppUtils isNullStr:paramStr]) {
        params = [AppUtils objectWithJsonString:paramStr];
    }
    [AppUtils trackMTAEventNo:[NSString stringWithFormat:@"%@",eventNo] parameters:params];
}

@end
